package com.longge;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class MergeArray {
    List<int[]> arr = new ArrayList<>();

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[1]));
        int[] mergeArr = intervals[0];
        for (int i = 1; i < intervals.length; i++) {
            mergeArr = mergeArr(mergeArr, intervals[i]);
        }
        arr.add(mergeArr);
        return arr.toArray(new int[][]{});
    }

    private int[] mergeArr(int[] one, int[] two) {
        if (one[1] < two[0]) {
            arr.add(one);
            return two;
        }
        return new int[]{Math.min(one[0], two[0]), Math.max(one[1], two[1])};

    }
}
